﻿using SBlogCore.Common.App;
using SBlogCore.Entitys.SysOrgManager;
using SBlogCore.WebAdminApplication.SysUserManager.Dto;
using SBlogCore.WebAdminApplication.SysUserManager.IServices;
using SBlogCore.Entitys.SysUserManager;
using SBlogCore.WebAdminApplication.SysManager.IServices;
using SBlogCore.WebAdminApplication.SysOrgManager.IServices;

namespace SBlogCore.WebAdminApplication.SysUserManager.Serivices
{
    public class SysUserInfoService : ISysUserInfoService
    {
        private readonly IRepository<SysUserInfo> _sysUserInfo;
        private readonly ISysFileInfoService _sysFileInfoService;
        private readonly ISysOrgInfoService _sysOrgInfoService;

        public SysUserInfoService(
            IRepository<SysUserInfo> sysUserInfo
            ,ISysFileInfoService sysFileInfoService
            ,ISysOrgInfoService sysOrgInfoService)
        {
            this._sysUserInfo = sysUserInfo;
            this._sysFileInfoService = sysFileInfoService;
            this._sysOrgInfoService = sysOrgInfoService;
        }
        /// <summary>
        /// 按条件查询列表
        /// </summary>
        /// <param name="inPut"></param>
        /// <returns></returns>
        public async Task<PageList<SysUserInfo>> GetUserList(SysUserInfoQueryInPut inPut)
        {
            Expression<Func<SysUserInfo, bool>> expression = w => true;
            if (!string.IsNullOrEmpty(inPut.UserName))
            {
                expression=expression.And(w => w.UserName != null && w.UserName.Contains(inPut.UserName));
            }
            if (!string.IsNullOrEmpty(inPut.Account))
            {
                expression = expression.And(w => w.Account == inPut.Account);
            }
            if (!string.IsNullOrEmpty(inPut.Phone))
            {
                expression = expression.And(w => w.Phone != null &&  w.Phone.Contains(inPut.Phone) );
            }
            if (!string.IsNullOrEmpty(inPut.Email))
            {
                expression = expression.And(w => w.Email != null && w.Email.Contains(inPut.Email));
            }
            if (inPut.Sex.HasValue)
            {
                expression = expression.And(w => w.Sex == inPut.Sex);
            }
            if (inPut.SysOrgId.HasValue)
            {
                var sysOrgId = inPut.SysOrgId.Value.ToString();
                expression = expression.And(w => w.SysOrgInfo != null && w.SysOrgInfo.LineNode != null && w.SysOrgInfo.LineNode.Contains(sysOrgId));
            }
            PageList<SysUserInfo>  list = await _sysUserInfo
                .Where(expression)
                .Include(w=>w.SysOrgInfo)
                .Include(w=>w.SysFileMap)
                .ThenInclude(w=>w!.SysFileInfo)
                .ToPagedListAsync(inPut.PageIndex??1, inPut.PageSize??10);
            return list;
        }
        /// <summary>
        /// 按ID查询用户单条信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public async Task<SysUserInfo> GetUserInfo(long id)
        {
            var info = await _sysUserInfo.Where(w=>w.Id== id)
                .Include(w => w.SysFileMap)
                .ThenInclude(w => w!.SysFileInfo)
                .FirstAsync();
            return info;
        }
        /// <summary>
        /// 按ID查询用户单条信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns></returns>
        public async Task<SysUserInfo> GetUserInfoById(long id)
        {
            var info = await _sysUserInfo.FindByIdAsync(id);
            if (info == null)
                throw SBlogCoreException.Say($"用户不存在！");
            return info;
        }

        public async Task<SysUserInfo> GetUserInfoByAccount(string account)
        {
            var info= await _sysUserInfo.FirstOrDefaultAsync(w => w.Account == account);
            if (info == null)
                throw SBlogCoreException.Say($"用户不存在！");
            return info.Adapt<SysUserInfo>();
        }
        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<SysUserInfo> GetLoginUserInfo()
        {
            var userToken = AppBase.GetJwtUser();
            if (userToken == null)
                throw SBlogCoreException.Say("登录异常，请重新登录！");
            SysUserInfo infuser = await GetUserInfo(userToken.Uid);
            return infuser;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<long> AddUserInfo(SysUserInfoInput input)
        {
            if (await AnyAccount(input.Account!))
                throw SBlogCoreException.Say($"当前账号已存在！");
            if (!string.IsNullOrEmpty(input.Email) && await AnyEmail(input.Email))
                throw SBlogCoreException.Say($"当前邮箱已存在！");
            SysUserInfo info = input.Adapt<SysUserInfo>();
            info.PassWord = "123456";
            if (input.SysOrgId.HasValue)
            {
                SysOrgInfo orgInfo = await _sysOrgInfoService.GetSysOrgInfoById(input.SysOrgId.Value);
                if (orgInfo.LineNode != null)
                {
                    var plantIds = orgInfo.LineNode.TrimStart(new[] { '|' }).Split('|');
                    info.PlantId = long.Parse(plantIds.First());
                }
            }
            var res=await _sysUserInfo.InsertAsync(info);
            if (info.PhotoId != null)
                await _sysFileInfoService.SaveFileMapToData<SysUserInfo>(info.Id, info.PhotoId.Value);
            return res.Id;
        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateUserInfo(SysUserInfoEditInput input)
        {
            var info = await GetUserInfoById(input.Id!.Value);
            if (input.Email != info.Email && await AnyEmail(input.Email!))
                throw SBlogCoreException.Say($"当前邮箱已存在！");
            info.UserName = input.UserName;
            info.Age = input.Age;
            info.Sex = input.Sex;
            info.Phone = input.Phone;
            info.Email = input.Email;
            info.Birthday = input.Birthday;
            info.PhotoId = input.PhotoId;
            info.SysOrgId = input.SysOrgId;
            info.Tag = input.Tag;
            if (input.SysOrgId.HasValue)
            {
               SysOrgInfo orgInfo= await _sysOrgInfoService.GetSysOrgInfoById(input.SysOrgId.Value);
               if (orgInfo.LineNode != null)
               {
                   var plantIds = orgInfo.LineNode.TrimStart(new[] { '|' }).Split('|');
                   info.PlantId = long.Parse(plantIds.First());
               }
            }
            await _sysUserInfo.UpdateAsync(info);
            if (info.PhotoId != null)
                await _sysFileInfoService.SaveFileMapToData<SysUserInfo>(info.Id, info.PhotoId.Value);
        }

        /// <summary>
        /// 判断账号是否存在
        /// </summary>
        /// <param name="account"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> AnyAccount(string account,long? id=null)
        {
            Expression<Func<SysUserInfo, bool>> expression = w => w.Account == account;
            if (id.HasValue)
            {
                expression = expression.And(w => w.Id != id);
            }
            return await _sysUserInfo.AnyAsync(expression);
        }

        /// <summary>
        /// 判断邮箱是否存在
        /// </summary>
        /// <param name="email"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> AnyEmail(string email, long? id = null)
        {
            Expression<Func<SysUserInfo, bool>> expression = w => w.Email == email;
            if (id.HasValue)
            {
                expression = expression.And(w => w.Id != id);
            }
            return await _sysUserInfo.AnyAsync(expression);
        }
        /// <summary>
        /// 更换用户头像
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="photoId"></param>
        /// <returns></returns>
        public async Task UpdateUserPhoto(long userId, long photoId)
        {
            var info = await GetUserInfoById(userId);
            info.PhotoId = photoId;
            await _sysUserInfo.UpdateNowAsync(info);
        }
        /// <summary>
        ///删除用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>

        public async Task DeleteUserInfo(long userId)
        {
            var info = await GetUserInfoById(userId);
            await _sysUserInfo.DeleteNowAsync(info);
        }

        /// <summary>
        /// 根据原密码修改用户密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="oldPassWord"></param>
        /// <param name="newPassWord"></param>
        /// <returns></returns>
        public async Task UpdateUserPassWord(long userId, string oldPassWord,string newPassWord)
        {
            var info = await GetUserInfoById(userId);
            if (info.PassWord!.Equals(oldPassWord))
                throw SBlogCoreException.Say($"原密码输入错误！");
            info.PassWord = newPassWord;
            await _sysUserInfo.UpdateNowAsync(info);
        }

        /// <summary>
        /// 更换用户密码
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public async Task UpdateUserPassWord(long userId, string passWord)
        {
            var info = await GetUserInfoById(userId);
            info.PassWord = passWord;
            await _sysUserInfo.UpdateNowAsync(info);
        }
    }
}
